import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export type Log = {
  date: Date;
  id: string;
  interface: string;
  ip: string;
  message: string;
  uri: string;
  username: string;
};

export const useOperatingLogStore = defineStore('OperatingLog', () => {
  const allOperatings = ref([] as Log[]);
  const loadedOperatings = ref(false);
  const setAllOperatings = (Operatings: Log[]) => (
    (allOperatings.value = Operatings), (loadedOperatings.value = true)
  );
  const getOperatingLogData = async () => {
    const OperatingLogs = await cutOperatingLog(
      '/redfish/v1/Managers/bmc/LogServices/AuditLog/Entries',
    );
    setAllOperatings(OperatingLogs);
  };
  const cutOperatingLog = async (url: string) => {
    return await api
      .get(url)
      .then(async ({ data }) => {
        let OperatingLogs = data.Members.map(
          (log: {
            [x: string]: any;
            Created?: any;
            Id?: any;
            Message?: any;
            Oem?: any;
          }) => {
            const { Created, Id, Message, Oem } = log;
            return {
              id: Id,
              date: new Date(Created),
              message: Message,
              uri: log['@odata.id'],
              interface: Oem[0],
              ip: Oem[1],
              username: Oem[2],
            };
          },
        );
        if (data['Members@odata.nextLink']) {
          OperatingLogs = [
            ...OperatingLogs,
            ...(await cutOperatingLog(data['Members@odata.nextLink'])),
          ];
        }
        return OperatingLogs;
      })
      .catch((error) => {
        console.log('Operating Log Data:', error);
      });
  };

  const deleteAllOperatingLogs = async (data: string | any[]) => {
    return await api
      .post(
        '/redfish/v1/Managers/bmc/LogServices/AuditLog/Actions/LogService.ClearLog',
        {},
        undefined,
      )
      .then(() => getOperatingLogData())
      .then(() => t('pageOperatingLogs.toast.successDelete', data.length))
      .catch((error) => {
        console.log(error);
        throw new Error(t('pageOperatingLogs.toast.errorDelete', data.length));
      });
  };

  const download = async () => {
    return await api
      .get('/download/audit')
      .then(() => {
        return 'Success';
      })
      .catch(() => {
        throw new Error('Failed');
      });
  };
  return {
    allOperatings,
    loadedOperatings,
    setAllOperatings,
    getOperatingLogData,
    cutOperatingLog,
    deleteAllOperatingLogs,
    download,
  };
});
